<template>
	<!-- <el-dialog v-model="visible" append-to-body draggable :title="`上传${title}`" width="900px"> -->
	<!-- <el-tabs v-model="active" stretch type="border-card" @tab-click="onTabClickHandle"> -->
	<!-- <el-tab-pane :label="`上传${title}`" :name="0"> -->
	<div class="v--upload-file-list" :class="{ cantclick: fileList.length == 1 }">
		<div class="v-upload-dragger" ref="draggerDom">
			<UploadFilled class="v-upload-icon"></UploadFilled>
			<div class="v-upload-text"><span>点击上传</span></div>
			<span>最多上传1个文件</span>
			<input
				:accept="accept"
				class="v-upload-input"
				type="file"
				ref="uploadInput"
				:multiple="max == 1"
				@change="onUpload"
			/>
		</div>
		<div v-if="provisionalIs" class="provisionalIs">
			<plus-item :provisional="provisionalIs"></plus-item>
		</div>
	</div>
	<!-- <div class="uploaded-list max-height">
					<div class="uploaded-list-item" :class="{ active: listUrl.includes(item.url) }"
						v-for="(item, index) in indexedDBList" :key="index" @click="onChooseInIndexedDB(item)"
						:title="item.name || item.url.split('/').pop()">
						<plus-item :url="item.name || item.url" :provisional="item.provisional"></plus-item>
						<el-button type="danger" icon="Close" circle class="uploaded-list-delete" size="default"
							@click.stop="onDeleteIndexedDB(item)" />
					</div>
				</div> -->
	<!-- </el-tab-pane> -->
	<!-- <el-tab-pane :label="`选择${title}`" :name="1">
				<el-row justify="end" :gutter="15">
					<el-col :span="7">
						<el-input
							v-model="resourceName"
							placeholder="请输入要搜索的文件名"
							clearable
							@keydown.enter="onSearchTableData"
						></el-input>
					</el-col>
					<el-col :span="3">
						<el-button icon="Search" type="primary" @click="onSearchTableData">搜索</el-button>
					</el-col>
				</el-row>
				<div class="uploaded-list">
					<div
						class="uploaded-list-item"
						:class="{ active: listUrl.includes(item.resourceUrl) }"
						v-for="(item, index) in tableData"
						:key="index"
						@click="
							onChooseInIndexedDB({
								url: item.resourceUrl,
								name: item.resourceName,
							})
						"
						:title="item.resourceUrl.split('/').pop()"
					>
						<plus-item :url="item.resourceUrl"></plus-item>
					</div>
				</div>
				<el-empty v-if="!tableData.length" :image-size="150" description="未找到文件" />
				<el-row justify="center">
					<el-pagination
						v-model:current-page="current"
						hide-on-single-page
						layout="prev, pager, next"
						:total="total"
						@current-change="onCurrentChange"
					/>
				</el-row>
			</el-tab-pane> -->
	<!-- <el-tab-pane :label="`${title}链接`" :name="2" v-if="props.type === 'image'">
				<div class="uploaded-link">
					<div class="uploaded-title">请输入图片链接</div>
					<el-input
						class="uploaded-link-input"
						size="large"
						placeholder="请输入图片链接"
						v-model="imageLink"
						clearable
						@keydown.enter="toAnalysisLink"
					></el-input>
					<el-button :disabled="!imageLink" type="primary" icon="Check" @click="toAnalysisLink">
						确定
					</el-button>
				</div>
			</el-tab-pane> -->
	<!-- </el-tabs> -->
	<!-- <template #footer>
		<el-button type="danger" icon="Close" @click="onCancel">取消</el-button>
		<el-button type="success" icon="Check" @click="onConfirm">确定</el-button>
	</template> -->
	<!-- </el-dialog> -->
</template>

<script setup>
import { ElMessage, ElMessageBox } from "element-plus"
import { computed } from "vue"
import { useUpload } from "../modules/useUpload"
import useDrop from "../modules/useDrop"
import { isImage, isVideo, image2Blob } from "/plugins/file"
import { useIndexedDBStore } from "/store/indexedDB"
import plusItem from "./plus-item.vue"
import { getAxios } from "/axios"

const indexedDBStore = useIndexedDBStore()

const props = defineProps({
	modelValue: {
		type: Boolean,
		default: false,
	},
	type: {
		type: String,
		default: "image",
	},
	accept: {
		type: String,
		default: "image/*",
	},
	max: {
		type: [String, Number],
		default: -1,
	},
	fileList: {
		type: Array,
		default: () => [],
	},
})

const emits = defineEmits(["update:modelValue", "update:fileList", "on-success"])

const uploadInput = shallowRef()
const draggerDom = shallowRef()
const active = shallowRef(0)
const indexedDBList = shallowRef([])
const resourceName = ref("")
const tableData = ref([])
const current = ref(1)
const total = ref(0)
const provisionalIs = ref(false)

function onTabClickHandle(pane) {
	if (pane.paneName === 1) {
		getTableData()
	}
}

async function getTableData() {
	const { records, total: tableDataTotal } = await getAxios("/system/sysOssRecord/page", {
		current: current.value,
		size: 10,
		resourceName: resourceName.value,
	})
	total.value = +tableDataTotal
	tableData.value = records
}
function onSearchTableData() {
	current.value = 1
	total.value = 0
	tableData.value = []
	getTableData()
}
function onCurrentChange() {
	getTableData()
}

async function getIndexedDBList() {
	const totalList = await indexedDBStore.getAll("upload-file")
	if (props.type === "image") {
		indexedDBList.value = totalList.filter(item => isImage(item.name))
	} else if (props.type === "video") {
		indexedDBList.value = totalList.filter(item => isVideo(item.name))
	} else {
		indexedDBList.value = totalList
	}
	if (indexedDBList.value.length != 0) {
		await indexedDBStore.delete("upload-file", indexedDBList.value[0].id)
	}
}
const title = computed(() => {
	switch (props.type) {
		case "image":
			return "图片"
		case "video":
			return "视频"
		case "file":
			return "文件"
	}
})
const visible = computed({
	get() {
		if (props.modelValue) {
			getIndexedDBList()
			list.value = [].concat(fileList.value)
			nextTick().then(createHandler)
		}
		return props.modelValue
	},
	set(value) {
		emits("update:modelValue", value)
	},
})
const fileList = computed({
	get() {
		list.value = [].concat(props.fileList || [])
		return props.fileList || []
	},
	set(value) {
		emits("update:fileList", value)
	},
})
const list = ref([])
const listUrl = computed(() => list.value.map(item => item.url))
const couldUpload = computed(() => {
	if (props.max === -1) {
		return true
	}
	return props.fileList.length < props.max
})

const { httpRequest } = useUpload(uploadInput)
const { createHandler } = useDrop(
	draggerDom,
	httpRequest,
	couldUpload,
	result => {
		if (result.length >= 2) {
			return ElMessage.error("只能上传一个文件")
		}
		list.value = list.value.concat([...result])
		getIndexedDBList()
	},
	false
)
async function onUpload() {
	if (!couldUpload.value) {
		throw new Error("禁止上传")
	}
	let textName = [...uploadInput.value.files].map(item => {
		return item.name
	})
	let textType = textName[0].match(/\.([^\.]+)$/)[1]
	if (textType == "mp4") {
	}
	switch (textType) {
		case "ppt":
		case "excel":
		case "word":
		case "pdf":
		case "doc":
		case "docx":
		case "excel":
		case "image":
		case "png":
		case "md":
		case "jpg":
		case "imge":
		case "bmp":
		case "xls":
		case "xlsx":
		case "log":
		case "txt":
			break
		default:
			return ElMessage.error("暂不支持")
			break
	}

	provisionalIs.value = true
	const file = [...uploadInput.value.files].map(item => {
		return {
			name: item.name,
			url: "",
			file: item,
			provisional: true,
		}
	})
	indexedDBList.value = indexedDBList.value.concat(file)
	const result = await httpRequest()
	fileList.value = fileList.value.filter(item => !item.provisional).concat([...result])
	indexedDBList.value.map(item => {
		if (item.provisional) {
			item.provisional = false
		}
	})
	getIndexedDBList()
	emits("on-success", result)
	setTimeout(() => {
		visible.value = false
		provisionalIs.value = false
	}, 300)
	return result
}

function onChooseInIndexedDB(item) {
	if (props.type === "image") {
		if (!isImage(item.url)) return
	} else if (props.type === "video") {
		if (!isVideo(item.url)) return
	}
	const index = listUrl.value.indexOf(item.url)
	if (!~index) {
		list.value.push(item)
	} else {
		list.value.splice(index, 1)
	}
}
async function onDeleteIndexedDB(item) {
	try {
		await ElMessageBox.confirm(`确定从缓存删除这${title.value}吗？`, "提示", {
			confirmButtonText: "确定",
			cancelButtonText: "取消",
			type: "warning",
		})
		await indexedDBStore.delete("upload-file", item.id)
		getIndexedDBList()
	} catch (error) {}
}

const imageLink = ref("")
function toAnalysisLink() {
	if (imageLink.value === "" || imageLink.value === null) return
	const image = new Image()
	const name = imageLink.value.split("/").pop()
	image.src = imageLink.value
	image.crossOrigin = "Anonymous"
	image.onload = async () => {
		try {
			const file = new File([image2Blob(image)], name, {
				type: "image/png",
			})
			const result = await httpRequest([file])
			fileList.value = fileList.value.concat([...result])
			getIndexedDBList()
			emits("on-success", result)
			visible.value = false
		} catch (error) {
			ElMessage.error(`获取${title.value}错误或${title.value}禁止读取`)
		}
	}
	image.onerror = () => {
		ElMessage.error(`获取${title.value}错误或${title.value}禁止读取`)
	}
}

function onConfirm() {
	fileList.value = [].concat(list.value)
	emits("on-success", [].concat(list.value))
	onCancel()
}
function onCancel() {
	visible.value = false
	list.value = [].concat(fileList.value || [])
}
</script>

<style lang="scss" scoped>
.v--upload-file-list {
	width: 250px;
	position: relative;

	.v-upload-dragger {
		width: 100%;
	}

	// .provisionalIs {
	// position: absolute;
	// width: 300px;
	// height: 200px;
	// left: 50%;
	// top: 50%;
	// }
}
.cantclick {
	pointer-events: none;
	cursor: not-allowed;
}
</style>
